<template>
  <div class="app-container">
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openPic"
      width="500px"
      append-to-body
    >
      <el-form ref="formPic" :model="formPic" :rules="rules" label-width="80px">
        <!-- <el-form-item label="链接地址" prop="links">
          <el-input v-model="formPic.links" placeholder="请输入链接地址" />
        </el-form-item> -->
        <el-form-item label="描述" prop="discription">
          <el-input
            v-model="formPic.discription"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="图片" prop="name">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccessActivity"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
          >
            <img
              v-if="formPic.filePath"
              :src="BaseUrl + formPic.filePath"
              class="avatar"
              style="width: 300px; height: 150px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formPic.status">
            <el-radio-button label="1">正常</el-radio-button>
            <el-radio-button label="0">停用</el-radio-button>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formPic.sort"
            :min="1"
            :max="100"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitformPic">确 定</el-button>
        <el-button @click="cancelPic">取 消</el-button>
      </div>
    </el-dialog>

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="新闻状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          @keyup.enter.native="handleQuery"
        >
          <el-option label="正常" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pc:news:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pc:news:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pc:news:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="newsList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="新闻ID" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <!-- <el-table-column label="新闻类型" align="center" prop="type" />
      <el-table-column
        label="新闻内容"
        align="center"
        prop="context"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <div
            v-html="scope.row.context"
            style="width: 200px; height: 150px"
          ></div>
        </template>
      </el-table-column>
      <el-table-column label="新闻状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <div slot="reference" class="name-wrapper">
              <el-tag
                size="medium"
                :type="scope.row.status === 0 ? 'danger' : 'success'"
                >{{ scope.row.status === 0 ? "关闭" : "正常" }}</el-tag
              >
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        prop="filePath"
        align="center"
        label="首页展示图片"
      >
      
        <template slot-scope="scope">
          <img
            v-show="scope.row.filePath"
            :src="BaseUrl + scope.row.filePath"
            min-width="300"
            height="150"
          />
        </template>
      </el-table-column>

      <el-table-column label="公告时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="discription" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pc:news:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
            v-hasPermi="['pc:news:edit']"
            >图片列表</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pc:news:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rowsPerPage"
      @pagination="getList"
    />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      @closed="closeItem"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入新闻标题" />
        </el-form-item>
        <!-- <el-form-item label="新闻类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择新闻类型">
            <el-option
              v-for="item in optionsType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="1">正常</el-radio-button>
            <el-radio-button label="0">停用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
            v-model="form.sendTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="新闻描述">
          <el-input type="textarea" v-model="form.discription"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容">
          <editor v-model="form.context" :min-height="192" />
        </el-form-item>

        <el-form-item v-show="form.filePath" label="新闻图片" prop="picture">
          <img :src="form.filePath" style="width: 300px; height: 150px" />
        </el-form-item>

        <el-form-item label="首页显示图片上传" prop="remark">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :before-upload="beforeUplad"
            :on-success="filesuccess"
            :headers="headers"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="图片列表"
      :visible.sync="open2"
      width="1200px"
      append-to-body
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddPic"
            v-hasPermi="['page:notice:add']"
            >新增</el-button
          >
        </el-col>
      </el-row>

      <div style="width: 90%">
        <el-table
          v-loading="loading"
          :data="list2"
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->

          <el-table-column
            header-align="center"
            prop="url"
            align="center"
            label="图片"
          >
            <template slot-scope="scope">
              <el-popover placement="top-start" trigger="click">
                <a
                  :href="BaseUrl + scope.row.filePath"
                  target="_blank"
                  title="查看最大化图片"
                >
                  <img
                    :src="BaseUrl + scope.row.filePath"
                    min-width="300"
                    height="300"
                  />
                </a>
                <img
                  slot="reference"
                  :src="BaseUrl + scope.row.filePath"
                  min-width="100"
                  height="100"
                  style="cursor: pointer"
                />
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column label="链接" align="center" prop="links" /> -->
          <el-table-column label="活动描述" align="center" prop="discription" />
          <!-- <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <div slot="reference" class="name-wrapper">
                  <el-tag
                    size="medium"
                    :type="scope.row.status === 0 ? 'danger' : 'success'"
                    >{{ scope.row.status === 0 ? "停用" : "正常" }}</el-tag
                  >
                </div>
              </el-popover>
            </template>
          </el-table-column> -->
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdatePic(scope.row)"
                v-hasPermi="['game:banner:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeletePic(scope.row)"
                v-hasPermi="['game:banner:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.rowsPerPage"
          :page-sizes="pageSizes"
          @pagination="getListActivity"
        /> -->
      </div>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel2">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listNews,
  getNews,
  delNews,
  addNews,
  updateNews,
  delNewsByIds,
  updatePic,
  delPic,
} from "@/api/page/photo";
import { getToken } from "@/utils/auth";
import { getFilebyId, delFilebyId } from "@/api/tool/file";
export default {
  name: "News",
  data() {
    return {
      isupload: false,
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      BaseUrl: process.env.VUE_APP_BASE_API,
      uploadUrl: process.env.VUE_APP_BASE_API + "/officialWebsite/news/upload", // 上传的图片服务器地址
      options: [
        {
          label: "1",
          value: "正常",
          id: 0,
        },
        {
          label: "0",
          value: "关闭",
          id: 1,
        },
      ],
      openPic: false,
      formPic: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻表格数据
      newsList: [],
      list2: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        page: 1,
        rowsPerPage: 10,
        title: null,
        context: null,
        status: null,
        pic: null,
      },
      activeId: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "新闻标题不能为空", trigger: "blur" },
        ],
        newsType: [
          { required: true, message: "新闻类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG / PNG格式!");
      }
      if (!isLt2M && !isPNG) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    },

    //上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    // 品牌活动上传
    handleAvatarSuccessActivity(res, file) {
      if (res.code == 200) {
        // this.isupload = true;
        this.formPic.fileId = res.data;
        // this.sizeForm.fileList.push(file);
        getFilebyId(res.data).then((res) => {
          if (res.code === 200) {
            this.formPic.filePath = res.data.filePath;
            this.$message({
              message: "文件上传成功",
              type: "success",
              duration: 1500,
            });
          }
        });
        console.log("数据" + res.data);
      }
    },

    beforeUplad(file) {
      // if (this.form.fileId) {
      //   delFilebyId(this.form.fileId).then((res) => {
      //     if (res && res.code === 200) {
      //       // this.$message({
      //       //   message: "文件删除成功",
      //       //   type: "success",
      //       //   duration: 1500,
      //       // });
      //     } else {
      //       this.$message.error(data.msg);
      //     }
      //   });
      // }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 上传成功后的回调函数
    filesuccess(res, file, fileList) {
      if (res.code == 200) {
        this.isupload = true;
        this.form.fileId = res.data;
        // this.sizeForm.fileList.push(file);
        getFilebyId(res.data).then((res) => {
          if (res.code === 200) {
            this.form.filePath =
              process.env.VUE_APP_BASE_API + res.data.filePath;
            this.$message({
              message: "文件上传成功",
              type: "success",
              duration: 1500,
            });
          }
        });
        console.log("数据" + res.data);
      }
    },

    /** 查询新闻列表 */
    getList() {
      this.loading = true;
      listNews(this.queryParams).then((response) => {
        this.newsList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      //   if (this.form.fileId && this.isupload) {
      //     delFilebyId(this.form.fileId).then((res) => {
      //       if (res && res.code === 200) {
      //         this.$message({
      //           message: "文件取消上传",
      //           type: "success",
      //           duration: 1500,
      //         });
      //       } else {
      //         this.$message.error(data.msg);
      //       }
      //     });
      //   }
      this.reset();
    },

    closeItem() {
      this.form = {};
    },

    cancel2() {
      this.open2 = false;
      this.reset2();
      this.activeId = "";
    },
    cancelPic() {
      this.openPic = false;
      this.reset2();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        context: null,
        status: null,
        fileId: null,
        fileName: null,
        filePath: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        sendTime: null,
        discription: null,
        sort: null,
      };
      this.fileList = [];
      this.isupload = false;
      this.resetForm("form");
    },
    reset2() {
      this.formPic = {
        id: null,
        fileId: null,
        fileName: null,
        filePath: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        discription: null,
        sort: null,
      };
      // this.list2 = [];
      this.resetForm("formPic");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌活动";
    },

    handleAddPic() {
      this.reset2();
      this.openPic = true;
      this.title = "添加图片";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getNews(id).then((response) => {
        // this.form = response.data;
        this.form = JSON.parse(
          JSON.stringify(this.newsList.filter((e) => e.id == row.id)[0])
        );
        // if (response.data.filePath) {
        //   this.form.filePath =
        //     process.env.VUE_APP_BASE_API + response.data.filePath;
        // }
        this.open = true;
        this.title = "修改品牌活动";
      });
    },

    handleUpdatePic(row) {
      this.reset2();
      const id = row.id || this.ids;

      this.formPic = JSON.parse(
        JSON.stringify(this.list2.filter((e) => e.id == row.id)[0])
      );
      this.openPic = true;
      this.title = "修改图片";
    },

    handleUpdate2(row) {
      this.reset2();
      this.activeId = row.id;
      const id = row.id || this.ids;
      getNews(id).then((response) => {
        this.list2 = response.data;
        this.open2 = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateNews(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNews(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      this.fileList = [];
    },

    // 图片提交
    submitformPic() {
      this.$refs["formPic"].validate((valid) => {
        if (valid) {
          this.formPic.photoId = this.activeId;
          if (this.formPic.id != null) {
            updatePic(this.formPic).then((response) => {
              this.$modal.msgSuccess("修改成功");

              getNews(this.activeId).then((response) => {
                this.list2 = response.data;
              });
              this.openPic = false;
            });
          } else {
            updatePic(this.formPic).then((response) => {
              this.$modal.msgSuccess("新增成功");
              getNews(this.activeId).then((response) => {
                this.list2 = response.data;
              });
              this.openPic = false;
            });
          }
        }
      });
      this.formPic = {};
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除品牌活动编号为"' + id + '"的数据项？')
        .then(function () {
          return delNews(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    handleDeletePic(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除图片编号为"' + id + '"的数据项？')
        .then(function () {
          return delPic(id);
        })
        .then(() => {
          getNews(this.activeId).then((response) => {
            this.list2 = response.data;
          });
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "pc/news/export",
        {
          ...this.queryParams,
        },
        `news_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
